package org.chimi.rr4s.rest;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.chimi.rr4s.application.AddActionService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 
 * @author Choi, Beom Kyun
 * 
 */
@Controller
public class AddActionApi {

	private AddActionService addActionService;

	@RequestMapping(value = "/api/action/view")
	@ResponseBody
	public AddActionResult addViewedAction(
			@RequestParam("sessionId") String sessionId,
			@RequestParam("userId") String userId,
			@RequestParam("itemId") String itemId,
			@RequestParam("itemType") String itemType,
			@RequestParam(value = "actionTime", required = false) String actionTimeValue) {
		addActionService.addViewedAction(sessionId, userId, itemId, itemType,
				parseTime(actionTimeValue));
		return new AddActionResult(true);
	}

	@RequestMapping(value = "/api/action/buy")
	@ResponseBody
	public AddActionResult addBoughtAction(
			@RequestParam("sessionId") String sessionId,
			@RequestParam("userId") String userId,
			@RequestParam("itemId") String itemId,
			@RequestParam("itemType") String itemType,
			@RequestParam(value = "actionTime", required = false) String actionTimeValue) {
		addActionService.addBoughtAction(sessionId, userId, itemId, itemType,
				parseTime(actionTimeValue));
		return new AddActionResult(true);
	}

	@RequestMapping(value = "/api/action/like")
	public AddActionResult addLikedAction(
			@RequestParam("sessionId") String sessionId,
			@RequestParam("userId") String userId,
			@RequestParam("itemId") String itemId,
			@RequestParam("itemType") String itemType,
			@RequestParam(value = "actionTime", required = false) String actionTimeValue) {
		addActionService.addLikedAction(sessionId, userId, itemId, itemType,
				parseTime(actionTimeValue));
		return new AddActionResult(true);
	}

	private Date parseTime(String actionTimeValue) {
		if (actionTimeValue == null) {
			return null;
		}
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
		try {
			return dateFormat.parse(actionTimeValue);
		} catch (ParseException e) {
			return null;
		}
	}
}
